package com.jlnk.androidfmc.model;

import static com.jlnk.androidfmc.database.ProductDatabaseHelper.COLUMN_PRODUCT_CATEGORY_ID;
import static com.jlnk.androidfmc.database.ProductDatabaseHelper.COLUMN_PRODUCT_DESCRIPTION;
import static com.jlnk.androidfmc.database.ProductDatabaseHelper.COLUMN_PRODUCT_IMAGE_PATH;
import static com.jlnk.androidfmc.database.ProductDatabaseHelper.COLUMN_PRODUCT_NAME;
import static com.jlnk.androidfmc.database.ProductDatabaseHelper.COLUMN_PRODUCT_PRICE;
import static com.jlnk.androidfmc.database.ProductDatabaseHelper.TABLE_PRODUCTS;

import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.jlnk.androidfmc.database.ProductDatabaseHelper;
import com.jlnk.androidfmc.entity.Product;

public class ReleaseModel {
    private ProductDatabaseHelper databaseHelper;
    public interface ReleaseItemCallback {
        void onSuccess();
        void onFailure(String errorMessage);
    }

    // 添加构造函数来初始化 databaseHelper
    public ReleaseModel(Context context) {
        // 确保 context 不为 null
        if (context != null) {
            this.databaseHelper = new ProductDatabaseHelper(context);
        } else {
            throw new IllegalArgumentException("Context cannot be null");
        }
    }

    public void releaseItem(Product product, final ReleaseItemCallback callback) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                SQLiteDatabase db = databaseHelper.getWritableDatabase();
                ContentValues values = new ContentValues();
                values.put(COLUMN_PRODUCT_NAME, product.getName());
                values.put(COLUMN_PRODUCT_DESCRIPTION, product.getDescription());
                values.put(COLUMN_PRODUCT_IMAGE_PATH, product.getImagePath());
                // 确保这里使用 Product 对象中的 categoryId
                values.put(COLUMN_PRODUCT_CATEGORY_ID, Integer.toString(product.getCategoryId()));
                values.put(COLUMN_PRODUCT_PRICE, String.valueOf(product.getPrice()));

                long result = db.insert(TABLE_PRODUCTS, null, values);
                db.close();

                if (result != -1) {
                    callback.onSuccess();
                } else {
                    callback.onFailure("发布失败，数据库插入错误");
                }
            }
        }).start();
    }
}